//
//  NetworkManager.swift
//  MyProject
//
//  Created by volantPig on 2020/11/10.
//

import UIKit
import Alamofire

typealias RequestSuccessBlock = (_ T: String ) -> Void
typealias RequestAnomalyBlock = (_ T: Int ) -> Void
typealias RequestFailureBlock = (_ T: Error? ) -> Void

var headerFields: HTTPHeaders {
    return [
        "Accept": "application/json",
        "Content-Type": "application/json",
        "terminalType": "CUSTOMER" //C端:CUSTOMER  B端:BUSINESS
    ]
}

class NetworkManager: NSObject {

    static let sharedSessionManager: Alamofire.Session = {
        let configuration = URLSessionConfiguration.default
        configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
        configuration.timeoutIntervalForRequest = 20
        let sharedSessionManager = Alamofire.Session.init(configuration: configuration, delegate: SessionDelegate())//(configuration: configuration)
        return sharedSessionManager
    }()
    
    class func getRequest(url: String!, params: [String: Any]?, requestHeaders: HTTPHeaders = headerFields, parameterEncoding: ParameterEncoding = JSONEncoding.default,  requestSuccessBlock: @escaping RequestSuccessBlock, requestAnomalyBlock: @escaping RequestAnomalyBlock, requestFailureBlock: @escaping RequestFailureBlock) {
        
        sharedSessionManager.request(url, method: .get, parameters: params, encoding: parameterEncoding, headers: requestHeaders).responseJSON { (response) in
            
            switch response.result {
            case .success(let success):
                if let statusCode = response.response?.statusCode, statusCode == 200 {
                    // 正常系
                    if let jsonString = Tools.dataChangeToJson(info: response.data!)
                    {
                        requestSuccessBlock(jsonString)
                    }
                } else {
                    requestAnomalyBlock(response.response?.statusCode ?? 0)
                }
            case .failure(let error):
                print("failure:\(error)")
            }
            
            
        }
    }
}
